﻿ 
namespace LinkerMode;

public class LinkerWebHost
{
    private readonly List<IFilter> _filters = new List<IFilter>();

    public void AddFilter(IFilter filter)
    {
        _filters.Add(filter);
    }

    public async Task ExecuteAsync(HttpContext context, IServlet servlet)
    {
        if (_filters.Any())
        {
            var filter = _filters[0];
            var chain = GetFilterChain(context, servlet, _filters.ToArray(), 1);

            await filter.InvokeAsync(context, chain);
        }
        else
        {
            await servlet.InvokeAsync(context);
        }
    }
    /// <summary>
    /// 构建链路器-- 递归
    /// </summary>
    /// <param name="context"></param>
    /// <param name="servlet"></param>
    /// <param name="filters"></param>
    /// <param name="index"></param>
    /// <returns></returns>
    private IChain GetFilterChain(HttpContext context, IServlet servlet, IFilter[] filters, int index)
    {
        if (index < filters.Length)
        {
            var filter = filters[index];
            var next = GetFilterChain(context, servlet, filters, index + 1);
            return new FilterChain(filter, context, next);
        }
        else
        {
            return new ServletChain(servlet, context);
        }
    }
}